(function( $ ){
    // 当domReady的时候开始初始化
    $(function() {
    	
		var $wrap = $('#uploader'),
		
		$filePicker = $(".add-btn"),
		
		// 优化retina, 在retina下这个值是2
		ratio = window.devicePixelRatio || 1,
		
		// 缩略图大小
		thumbnailWidth = 40 * ratio,
		thumbnailHeight = 40 * ratio,
		
		// 所有文件的进度信息，key为file id
		percentages = {},
		// 判断浏览器是否支持图片的base64
		isSupportBase64 = ( function() {
			var data = new Image();
			var support = true;
			data.onload = data.onerror = function() {
				if( this.width != 1 || this.height != 1 ) {
					support = false;
				}
			}
			data.src = "";
			return support;
		} )(),
		
		// 检测是否已经安装flash，检测flash的版本
		flashVersion = ( function() {
			var version;
			
			try {
				version = navigator.plugins[ 'Shockwave Flash' ];
				version = version.description;
			} catch ( ex ) {
				try {
					version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
					.GetVariable('$version');
				} catch ( ex2 ) {
					version = '0.0';
				}
			}
			version = version.match( /\d+/g );
			return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
		} )(),
		
		supportTransition = (function(){
			var s = document.createElement('p').style,
			r = 'transition' in s ||
			'WebkitTransition' in s ||
			'MozTransition' in s ||
			'msTransition' in s ||
			'OTransition' in s;
			s = null;
			return r;
		})(),
		
		// WebUploader实例
		uploader;
		
		if ( !WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) {
			
			// flash 安装了但是版本过低。
			if (flashVersion) {
				(function(container) {
					window['expressinstallcallback'] = function( state ) {
						switch(state) {
						case 'Download.Cancelled':
							alert('您取消了更新！')
							break;
							
						case 'Download.Failed':
							alert('安装失败')
							break;
							
						default:
							alert('安装已成功，请刷新！');
						break;
						}
						delete window['expressinstallcallback'];
					};
					
					var swf = './expressInstall.swf';
					// insert flash object
					var html = '<object type="application/' +
					'x-shockwave-flash" data="' +  swf + '" ';
					
					if (WebUploader.browser.ie) {
						html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
					}
					
					html += 'width="100%" height="100%" style="outline:0">'  +
					'<param name="movie" value="' + swf + '" />' +
					'<param name="wmode" value="transparent" />' +
					'<param name="allowscriptaccess" value="always" />' +
					'</object>';
					
					container.html(html);
					
				})($wrap);
				
				// 压根就没有安转。
			} else {
				$wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
			}
			
			return;
		} else if (!WebUploader.Uploader.support()) {
			alert( 'Web Uploader 不支持您的浏览器！');
			return;
		}
		// 实例化
		uploader = WebUploader.create({
			auto :true,
			server: 'uploadFile',
			swf: 'static/plugins/webuploader/dist/Uploader.swf',
			pick: {
				id: $filePicker
			},
			accept: {
				title: 'Images',
				extensions: 'gif,jpg,jpeg,bmp,png',
				mimeTypes: 'image/*'
			},
			thumb:{
				width: 40,
				height: 40,
				
			    // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
			    allowMagnify: true,

			    // 是否允许裁剪。
			    crop: true
			},
			disableGlobalDnd: true,
			fileNumLimit: 6,
			fileSizeLimit: 200 * 1024 * 1024,    // 200 M
			fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
		});
		
		uploader.on('ready', function() {
			window.uploader = uploader;
		});
		
		//当文件被加入队列以后触发。
		uploader.onFileQueued = function( file ) {
			console.log(file);
			var $li = $( '<div class="preview-photo" id="' + file.id + '">' +
					'<p class="imgWrap"></p>' + 
					'<img class="del-btn" src="static/ssjf/img/del_btn.png" />' + 
					'<div class="input-container"></div></div>').appendTo( $wrap ),
			imgWrap = $li.find( 'p.imgWrap' );
			
			uploader.makeThumb( file, function( error, src ) {
				var img;
				if( isSupportBase64 ) {
					img = $('<img class="preview-photo-photo" src="'+src+'">');
					imgWrap.append( img );
				}
			}, thumbnailWidth, thumbnailHeight );
			
			
			$li.on('click', '.del-btn', function() {
			    uploader.removeFile( file );
			})
		};
		
		//当文件被移除队列后触发。
		uploader.onFileDequeued = function( file ) {
			var $li = $('#'+file.id);
			$li.remove();
			var fileId = $li.find(".input-container input[name='fileId']").val();
			console.log(fileId);
			$.post("deleteFile",{id:fileId},function(result){
				console.log(result);
			});
		};
		
		uploader.onUploadError = function( file, reason ) {
			alert( 'Error: ' + file + '上传错误,'+  reason );
		};
		
		uploader.on('uploadSuccess',function(file,json){
			var $li = $('#'+file.id);
			var input = '<input type="hidden" for-multi="fileRel" name="fileId" value="'+json.fileId+'">';
			input += '<input type="hidden" for-multi="fileRel" name="remark" value="cover">';
			input += '<input type="hidden" for-multi="fileRel" name="fileType" value="image">';
			input += '<input type="hidden" for-multi="fileRel" name="fileFile" value="'+json.saveName+'">';
			input += '<input type="hidden" for-multi="fileRel" name="urlInfor" value="'+json.savePath+'">';
			$li.find(".input-container").append(input);
		});
		
    });

})( jQuery );